package com.example.ercmssystem2.repository;

import com.example.ercmssystem2.entity.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface DepartmentRepository extends JpaRepository<Department, Long> {

    // 查找所有启用的部门
    List<Department> findByEnabledTrue();

    // 根据父部门ID查找子部门
    List<Department> findByParentIdAndEnabledTrue(Long parentId);

    // 查找顶级部门（parentId为null的部门）
    List<Department> findByParentIdIsNullAndEnabledTrue();

    // 根据部门管理员ID查找部门
    List<Department> findByManagerIdAndEnabledTrue(Long managerId);

    // 根据部门名称查找部门
    Optional<Department> findByNameAndEnabledTrue(String name);

    // 检查部门名称是否存在（排除指定ID）
    @Query("SELECT COUNT(d) > 0 FROM Department d WHERE d.name = :name AND d.enabled = true AND d.id != :excludeId")
    boolean existsByNameAndEnabledTrueAndIdNot(@Param("name") String name, @Param("excludeId") Long excludeId);

    // 查找用户所在部门及其所有子部门
    @Query("SELECT d FROM Department d WHERE d.id = :departmentId OR d.parentId = :departmentId AND d.enabled = true")
    List<Department> findDepartmentAndChildren(@Param("departmentId") Long departmentId);

    // 查找部门的所有子部门（递归）
    @Query("SELECT d FROM Department d WHERE d.parentId = :departmentId AND d.enabled = true")
    List<Department> findAllChildrenRecursive(@Param("departmentId") Long departmentId);
} 